# -*- coding:utf-8 -*- 

"""
作者：luoyu
日期：2021年05月12日
"""
import time

import requests
import json
import re


def get_classid():
    cookies = {

    }

    headers = {
        
    }

    params = (
        ('cid', '10242406'),
        ('sign', 'sxyz62011005322'),
    )

    "cid=10242406&product_sign=sxyz62011005322"
    response = requests.get('https://www.xuetangx.com/api/v1/lms/learn/course/chapter', headers=headers, params=params)
    result = response.json()
    # print(result)
    classlst = result['data']['course_chapter']
    clssLst = []
    for item in classlst:
        q = json.dumps(item['section_leaf_list'], ensure_ascii=False)
        b = json.loads(q)
        for item2 in b:
            try:
                result2List = item2['leaf_list']
                for result2 in result2List:
                    if "测试题" in result2['name']:
                        clssLst.append(result2)
            except:
                pass
    questionLst = []
    for each in clssLst:
        question = {}
        question['name'] = each['name']
        question['id'] = each['id']
        questionLst.append(question)
    print(questionLst)
    return questionLst



def get_true_id(class_id):
    cookies = {
    }

    headers = {
         }

    params = {
        'sign': 'sxyz62011005322',
    }
    response = requests.get(f'https://www.xuetangx.com/api/v1/lms/learn/leaf_info/10242406/{class_id}/', headers=headers, params=params, cookies=cookies)
    true_id = response.json()["data"]["content_info"]["leaf_type_id"]
    print(true_id,class_id)
    # time.sleep(222)
    return  true_id

def get_answers(classId, trueId):
    cookies = {
         }

    headers = {
         }

    response = requests.get(f'https://www.xuetangx.com/api/v1/lms/exercise/get_exercise_list/{trueId}/4330939/', headers=headers, cookies=cookies)
    

    result = response.json()['data']['problems']
    problem_List = []
    for item in result:
        problem_dic = {}
        contains = item['content']["Body"]
        contains2 = re.findall('<p>(.*)', contains)

        problem_dic['question'] = contains2[0].replace("\u2002", "")
        options = item['content']["Options"]
        opt_lst = []
        # print(item)
        for opt in options:
            option = opt['key'] + "." + re.findall("<p>(.*)", opt["value"])[0]
            opt_lst.append(option)
            # print(option)
        answer = "None"
        try:
            answer = item['user']["answer"]
        except:
            print("get anwer Error！")
        problem_dic['option'] = opt_lst
        problem_dic['answer'] = answer
        problem_List.append(problem_dic)
    return problem_List


def main():
    classLst = get_classid()
    problemsList = []
    for item in classLst:
        class_Name = item['name']
        class_id = item['id']
        print(item)
        # break
        try:
            trueId = get_true_id(item['id'])
            problem_list = get_answers(class_id, trueId)

            problemDic = {}
            problemDic['class'] = class_Name
            problemDic['problems'] = problem_list
            problemsList.append(problemDic)
        except:
            print(f"error--?{item}")
    json_str = json.dumps(problemsList, ensure_ascii=False)
    with open('test_data.json', 'w', encoding='utf-8') as json_file:
        json_file.write(json_str)


if __name__ == '__main__':
    # get_answers(9260358, 989472)
    # main()
    main()